// store/modules/websocket.js
const state = {
    socket: null,
    messages: [],
  };
  
  const mutations = {
    SET_SOCKET(state, socket) {
      state.socket = socket;
    },
    ADD_MESSAGE(state, message) {
      state.messages.push(message);
    },
  };
  
  const actions = {
    connect({ commit }, userdata) {
        if(state.socket != null)return;
      const socketUrl = `ws://10.70.128.53:7090/ws?token=${userdata.token}`;
      const socket = new WebSocket(socketUrl);
  
      socket.onopen = () => {
        console.log("WebSocket connected!");
        commit('SET_SOCKET', socket);
      };

      //收到一条消息

  
      socket.onclose = () => {
        console.log("WebSocket disconnected!");
        commit('SET_SOCKET', null);
      };

      window.onbeforeunload = function() {
        socket.close();
      }
    },
  
    disconnect({ state }) {
      if (state.socket) {
        state.socket.close();
      }
    },
  };
  
  export default {
    namespaced: true,
    state,
    mutations,
    actions,
  };
  